<template>
  <div v-loading="loading">
    <FormContainer :column="3">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
        <el-form-item prop="qualityCheckContent" label="质检内容">
          <el-select v-model="formData.qualityCheckContent" filterable placeholder="请选择">
            <el-option v-for="(d,i) in inspectionContentList" :key="i" :value="d.dictCode" :label="d.dictName"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="showCall">
          <el-form-item prop="callCode" label="通话记录编号">
            <el-input v-model="formData.callCode" clearable placeholder="请输入编号"></el-input>
          </el-form-item>
          <el-form-item prop="callDate" label="通话时间">
            <el-date-picker v-model="formData.callDate" type="daterange" opt operator=">" :limite="new Date()" start-placeholder="开始时间" end-placeholder="结束时间" format="yyyy-MM-dd" clearable></el-date-picker>
          </el-form-item>
          <el-form-item prop="callType" label="呼叫类型">
            <SelectForDict :code.sync="formData.callType" dict-type-code="CALL_TYPE"></SelectForDict>
          </el-form-item>
          <el-form-item prop="callDurationBegin" label="通话时长">
            <div :class="$style.innerCenter">
              <el-input v-model="formData.callDurationBegin" v-number-input placeholder="最小时长" clearable></el-input>
              <span>-</span>
              <el-input v-model="formData.callDurationEnd" v-number-input placeholder="最大时长" clearable></el-input>
              <span>(秒)</span>
            </div>
          </el-form-item>
        </template>
        <el-form-item prop="businessType1" label="一级业务类型">
          <!-- <SearchSelectPicker
            :value.sync="formData.businessType1"
            :lable.sync="formData.businessType1Name"
            url="/call-center/api/v1/businessDeptRelation/page"
            :params="{query:{relationLevel:1},type:0}"
            value-name="relationCode"
            lable-name="relationName"
            @selectChange="formData.businessType2 = ''"
          ></SearchSelectPicker> -->
          <CustomDictSelect
            placeholder="请选择"
            dict-type-code="FIRST_LEVEL_BUSINESS_TYPE"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="formData.businessType1"
            :echo-name.sync="formData.businessType1Name"
            filterable
          ></CustomDictSelect>
        </el-form-item>
        <el-form-item prop="businessType2" label="二级业务类型">
          <!-- <SearchSelectPicker
            :value.sync="formData.businessType2"
            :lable.sync="formData.businessType2Name"
            url="/call-center/api/v1/businessDeptRelation/page"
            :params="{query:{relationLevel:2, parentRelationCode: formData.businessType1},type:0}"
            :parent-id="formData.businessType1"
            must-pid
            :disabled="formData.businessType1===''"
            value-name="relationCode"
            lable-name="relationName"
          ></SearchSelectPicker> -->
          <CustomDictSelect
            placeholder="请选择"
            dict-type-code="SECOND_LEVEL_BUSINESS_TYPE"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="formData.businessType2"
            :echo-lable.sync="formData.businessType2Name"
            filterable
          ></CustomDictSelect>
        </el-form-item>
        <template v-if="showWorkOrder">
          <el-form-item prop="workOrderCreateDate" label="工单创建时间">
            <el-date-picker v-model="formData.workOrderCreateDate" type="daterange" opt operator=">" :limite="new Date()" start-placeholder="开始时间" end-placeholder="结束时间" format="yyyy-MM-dd" clearable></el-date-picker>
          </el-form-item>
          <el-form-item prop="workOrderCode" label="工单编号">
            <el-input v-model="formData.workOrderCode" clearable placeholder="请输入编号"></el-input>
          </el-form-item>
        </template>
        <el-form-item prop="checkQuantity" label="受检量">
          <el-input v-model="formData.checkQuantity" v-number-input clearable placeholder="请输入受检量"></el-input>
        </el-form-item>
      </el-form>
    </FormContainer>
    <ButtonGroup :button="['save', 'genProject', 'prev']" @genProject="genProjectHandle" @prev="prevHandle" @save="saveHandle"></ButtonGroup>
  </div>
</template>

<script>
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import CustomDictSelect from '@/components/CustomDictSelect'
// import SearchSelectPicker from '@/components/SearchSelectPicker'
import ButtonGroup from './buttonGroup'
import { inspectionContentList } from '../../common'
import { qualityCheckProjectSaveScreening, qualityCheckProjectAdd, qualityCheckSave } from '@/api/inspection'
import { parseTime, numToString } from '@/utils'
export default {
  name: 'ContentFilter',
  components: {
    FormContainer,
    SelectForDict,
    // SearchSelectPicker,
    CustomDictSelect,
    ButtonGroup
  },
  props: {
    stepData: {
      type: Object,
      default: () => ({})
    },
    next: {
      type: String,
      default: undefined
    },
    prev: {
      type: String,
      default: undefined
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatorDate = (r, v, c) => {
      if (v && v.length === 2) {
        c()
      } else {
        c(new Error('请选择时间'))
      }
    }
    // 限制受检数量为120
    const validatorCheckQuantity = (r, v, c) => {
      if (v > 120) {
        c(new Error('受检数量不能大于120'))
      } else {
        c()
      }
    }
    // 验证通话时长
    const validatorCallDuration = (r, v, c) => {
      const min = this.formData.callDurationBegin
      const max = this.formData.callDurationEnd
      function True(v) {
        return (v !== '' && v !== undefined && v !== null)
      }
      if (!True(min) && !True(max)) {
        c(new Error('请输入通话时长'))
      } else {
        c()
      }
    }
    return {
      loading: false,
      formData: {
        qualityCheckContent: '',
        callDate: [],
        callDateBegin: '',
        callDateEnd: '',
        callType: '',
        callDurationBegin: '',
        callDurationEnd: '',
        businessType1: '',
        businessType1Name: '',
        businessType2: '',
        businessType2Name: '',
        workOrderCreateDate: [],
        workOrderCreateDateBegin: '',
        workOrderCreateDateEnd: '',
        callCode: '',
        workOrderCode: '',
        checkQuantity: ''
      },
      formRules: {
        qualityCheckContent: [{ required: true, message: '请选择质检内容', trigger: 'change' }],
        callDate: [{ required: true, type: 'array', validator: validatorDate, trigger: 'change' }],
        workOrderCreateDate: [{ required: true, type: 'array', validator: validatorDate, trigger: 'change' }],
        checkQuantity: [{ required: true, validator: validatorCheckQuantity, trigger: 'change' }],
        // 验证通话时长
        callDurationBegin: [{ required: true, validator: validatorCallDuration, trigger: 'change' }]
      },
      inspectionContentList
    }
  },
  computed: {
    showCall() {
      return ['1', '3', 1, 3].includes(this.formData.qualityCheckContent)
    },
    showWorkOrder() {
      return ['2', '3', 2, 3].includes(this.formData.qualityCheckContent)
    }
  },
  watch: {
    stepData: {
      handler(n) {
        if (Object.keys(n).length > 0) {
          this.initFormData()
        }
      },
      immediate: true
    }
  },
  methods: {
    initFormData() {
      // eslint-disable-next-line prefer-const
      for (let [k, v] of Object.entries(this.stepData)) {
        if (!Object.prototype.hasOwnProperty.call(this.formData, k)) {
          continue
        }
        if (this.$validateNone(v)) continue
        v = numToString(v)
        this.$set(this.formData, k, v)
      }
      if (this.stepData.callDateBegin && this.stepData.callDateEnd) {
        this.$set(this.formData, 'callDate', [this.stepData.callDateBegin, this.stepData.callDateEnd])
      }
      if (this.stepData.workOrderCreateDateBegin && this.stepData.workOrderCreateDateEnd) {
        this.$set(this.formData, 'workOrderCreateDate', [this.stepData.workOrderCreateDateBegin, this.stepData.workOrderCreateDateEnd])
      }
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    // 保存
    genData() {
      return this.$refs.form.validate().then(() => {
        const data = {}
        for (const [k, v] of Object.entries(this.formData)) {
          if (this.$validateNone(v)) continue
          data[k] = v
        }
        if (data.callDate && data.callDate.length === 2) {
          data.callDateBegin = parseTime(data.callDate[0], '{y}-{m}-{d}')
          data.callDateEnd = parseTime(data.callDate[1], '{y}-{m}-{d}')
        }
        delete data.callDate
        if (data.workOrderCreateDate && data.workOrderCreateDate.length === 2) {
          data.workOrderCreateDateBegin = parseTime(data.workOrderCreateDate[0], '{y}-{m}-{d}')
          data.workOrderCreateDateEnd = parseTime(data.workOrderCreateDate[1], '{y}-{m}-{d}')
        }
        delete data.workOrderCreateDate
        data.id = this.stepData.id
        data.qualityCheckContent = this.formData.qualityCheckContent
        return data
      })
    },
    saveHandle() {
      return this.genData().then(data => {
        return qualityCheckProjectSaveScreening(data).then(res => {
          this.$message.success('保存成功！')
          this.$emit('on-refresh')
        })
      })
    },
    genProjectHandle() {
      return this.genData().then(data => {
        this.loading = true
        return qualityCheckProjectAdd(data).then(res => {
          // {"new":1,"checked":1,"identifyingCode":"sdf234234fa"}
          const { identifyingCode, checked, addData } = (res.data || {})
          this.$message.success(`生成${addData}个任务！`)
          if (checked && identifyingCode) {
            return this.$msgbox({
              title: '提示',
              message: `已生成${addData}个任务！存在 ${checked} 个已质检项，是否生成任务？`,
              showCancelButton: true,
              type: 'warning'
            }).then(() => {
              return qualityCheckSave(identifyingCode).then(() => {
                this.$message.success(`生成${checked}个任务！， 共生成${addData + checked}个任务！`)
              })
            })
          }
        }).then(() => {
          this.$closePage(this.$route, { name: 'ItemManage' })
        }).finally(() => {
          this.loading = false
        })
      })
    },
    prevHandle() {
      this.$emit('input', this.prev)
    }
  }
}
</script>
<style lang="scss" module>
.innerCenter{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>*{
    margin-left: 5px;
  }
}
</style>
